package aigcAdminUtils

import (
	"os"
	"path/filepath"
	"strings"

	"gitee.com/wchpub/fnsvr"
)

type UploadSubPath string

const (
	UploadSubPathReferenceImages UploadSubPath = "reference_imgs" //参考图
	UploadSubPathWorkflowOut     UploadSubPath = "workflow_out"   //工作流输出
)

// 将图片保存到uploads目录
// 返回保存的完整路径
func CreateUploadFile(uploadPath string, subPath UploadSubPath, ext string, data []byte) (string, error) {
	var fileName string
	var imgPath string
	// 生成随机文件名
	for {
		fileName = strings.ToLower(fnsvr.GenerateRandomString(32)) + ext
		imgPath = filepath.Join(uploadPath, string(subPath), fileName[0:2], fileName[2:4])

		imgPathAndFile := filepath.Join(imgPath, fileName)

		ex, err := fnsvr.FileExists(imgPathAndFile)
		if err != nil {
			return "", err
		}
		if !ex {
			break
		}
	}

	// 确保输出目录存在
	if err := os.MkdirAll(imgPath, 0755); err != nil {
		return "", err
	}

	outputPathAndFile := filepath.Join(imgPath, fileName)
	// 保存图片
	outFile, err := os.Create(outputPathAndFile)
	if err != nil {
		return "", err
	}
	defer outFile.Close()

	_, err = outFile.Write(data)
	if err != nil {
		return "", err
	}

	return outputPathAndFile, nil
}
